<?php

/**
 * Framework_Module_User_Login
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Module
 * @filesource
 */

/**
 * Framework_Module_User_Login
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @package Module
 */
class Framework_Module_User_Login extends Framework_Module_User
{
  
	/**
     * $ownerTable
     *
     * @access      public
     * @var         object		$ownerTable      Owner Table object
     */
	private $ownerTable;
	
	/**
     * $openIDRequest
     *
     * @access      public
     * @var         object		$openIDRequest     OpenID request object
     */	
	private $openIDRequest = null;
		
	 
	/**
     * __construct
     *
     * Initializes the module: sets the default presenter, the allowed
     * conrollers, and the allowed events
     *
     * @access 		public
     * @return 		void
     */
	public function __construct()
	{
		parent::__construct();
		$this->presenter = 'Smarty';
		$this->moduleTplFile = 'login.tpl';
		 
		if (Framework::$request->isAjax()) {
			$this->presenter = 'Module';
		}
		 
		// Check for openID request
		if($this->session->openIDRequest) {
			$this->openIDRequest = $this->session->openIDRequest;
		}
	}

	/**
     * __default
     *
     * Generates login form
     *
     * @access 		public
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	public function __default()
	{

		 
		$form = Framework_Quickform::factory('loginOwner', 'post', Framework::$request->getBaseHTTPPath().'/-/User/Login', null, null, true);
		 
		$this->ownerTable = Framework_DB::tableFactory('Owner');
		 
		$cols = array('loginName', 'pWord');
		$this->ownerTable->addFormElements($form, $cols);
		 
		// Submit button
		$form->addElement('submit','btnSubmit','Login','class="button" id="ownerLoginButton"');
		 
		// Check for openID request
		if($this->openIDRequest || Framework::$request->isAjax()) {
			 $form->addElement('submit','btnCancel','Cancel','class="button jqmClose" id="cancelButton"');
		}

		// Filters
		$form->applyFilter('__ALL__','trim');
		 
		$form->addFormRule(array($this,'checkOwnerLogin'));
		 
		$this->forms['form'] = $form;
		
		
		if ($this->forms['form']->isSubmitted() && $this->openIDRequest && $this->forms['form']->getSubmitValue('btnCancel')) {
			$this->cancelOpenID();
			return true;
		}
		 
		// Process form
		if ($this->forms['form']->validate()) {
			$result = $this->forms['form']->process(array(&$this, 'processForm'));
			 return $result;
		}
	}


	/**
     * cancelOpenID
     *
     * 
     *
     * @access 		private
     * @return 		void
     */
	private function cancelOpenID()
	{
		$url = $this->openIDRequest->getCancelURL();
		
		$this->session->openIDRequest = null;
		
		Framework_Header::redirect($url);
	}

	 
	/**
     * checkOwnerLogin
     *
     * 
     *
     * @access 		public
     * @param		array		$fields		Form fields to check
     * @return 		mixed		Boolean true on success, an array on failure
     */
	public function checkOwnerLogin($fields)
	{
		 
		$queryArray = array(
			'sqlKey' => array(
				'select' => 'pWord',
				'where'  => 'loginName = ?',
				'get'    => 'row'
	  	    ),
	
			'params' => array($fields['loginName'])
		);
		
		$row = $this->ownerTable->select($queryArray);
		

		
		if (count($row)) {
			if (strcmp($row['pWord'], md5($fields['pWord'])) == 0){
				return true;
			} else {
				
				return array('loginName' => 'Invalid Login!');
			}
		} else {
			return array('loginName' => 'Invalid Login!');
		}
		 
	}

	/**
     * processForm
     *
     *
     * @access 		public
     * @param 		array		$data		Data to process
     * @return 		boolean		true
     */
	public function processForm($data)
	{

		$owner = new Framework_Owner($data['loginName']);
		$this->sessionLogin($owner->idSiteUser);
		$this->makeToken($owner);

		// Check for openID request
		if($this->openIDRequest) {
			
			Framework_Header::redirect(Framework::$request->getBaseHTTPPath().'/-/User/OpenIDServer?openIDLogin');
    
		}

		if (Framework::$request->isAjax()) {
			$this->setData('loginAjax', Framework::$request->getBaseHTTPPath().'/'.$owner->userName.'/CP');
		} else {
			// Otherwise redirect normally
			Framework_Header::redirect(Framework::$request->getBaseHTTPPath().'/'.$owner->userName.'/CP');
		}

		return true;
		 
	}

	/**
     * makeToken
     *
     *
     * @access 		public
     * @param 		object		$pwner		Owner object to make token from
     * @return 		mixed 		void, PEAR_Error on failure
     */
	private function makeToken($owner)
	{
		// PEAR RSA
		require_once 'Crypt/RSA.php';
		require_once 'Crypt/RSA/Key.php';
		 
		if (!strlen($owner->publicKey))
		return PEAR::raiseError('Bad Key');
		 
		$publicKey = Crypt_RSA_Key::fromString($owner->publicKey);
		$rsa_obj = new Crypt_RSA;
		if (!PEAR::isError($publicKey))
		return $rsa_obj->encrypt(md5($owner->pWord.$_SERVER['REMOTE_ADDR']), $publicKey);
		else
		return PEAR::raiseError('Bad Key');

		 
	}

	/**
     * __destruct
     *
     *
     * @access 		public
     * @return 		void
     */
	public function __destruct()
	{
		parent::__destruct();
	}
}


?>
